<?php

namespace addons\oil\listener\order;

use addons\oil\exception\Exception;
use addons\sum\model\Config as ConfigModel;
use addons\oil\model\Order;
use addons\sum\model\User;
use app\admin\model\sum\TeamOrderLog;
use think\Db;

/**
 * 订单确认收货
 */
class Confirm
{
    // 订单确认收货后
    public function orderConfirmAfter(&$params)
    {
        $order = $params['order'];
        $order = Order::where('id', $order['id'])->find();

        // 更新收货时间
        $order->ext = json_encode($order->setExt($order, ['confirm_time' => time()]));      // 收货时间
        $order->save();

        // 特价版返佣机制-一级二级返佣
        $config = ConfigModel::where('name', 'oil')->column('value', 'name');
        $oilConfig = json_decode($config['oil'], true);
        $base_money=$oilConfig['base_money'];
        $zhitui_ratio=$oilConfig['zhitui_ratio'];
        $jiantui_ratio=$oilConfig['jiantui_ratio'];
        $tuandui_ratio=$oilConfig['tuandui_ratio'];

        //增加用户加油量
        Db::name('user')->where('id',$order['user_id'])->setInc('litre',$order['litre']);

        $user=Db::name('user')->where('id',$order['user_id'])->find();
        if($user['pid']>0){//处理直推奖励
            $zhitui_money=$base_money*$order['litre']*$zhitui_ratio*0.01;
            if($zhitui_money>0){
                User::commission($zhitui_money,$user['pid'],'commission_income',$order['id'],'',['litre'=>$order['litre']],$order['user_id']);
            }
            $zhitui_user=Db::name('user')->where('id',$user['pid'])->find();//直推用户
            if($zhitui_user['pid']>0){//处理减推奖励
                $jiantui_money=$base_money*$order['litre']*$jiantui_ratio*0.01;
                if($jiantui_money>0){
                    User::commission($jiantui_money,$zhitui_user['pid'],'commission_income',$order['id'],'',['litre'=>$order['litre']],$order['user_id']);
                }
            }
        }
        if($user['did']>0){// 增加团队长加油订单记录
            $team_order_data=[];
            $team_order_data['user_id']=$user['did'];
            $team_order_data['order_user_id']=$order['user_id'];
            $team_order_data['order_id']=$order['id'];
            $team_order_data['litre']=$order['litre'];
            $team_order_data['money']=$base_money*$order['litre']*$tuandui_ratio*0.01;
            $team_order_data['createtime']=time();
            $team_order_data['updatetime']=time();
            $team_order_log=new TeamOrderLog();
            $team_order_log->save($team_order_data);
        }
        return $order;
    }
}
